<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 2020-06-17
 * Time: 16:17
 * 创建项目孵化
 */

namespace app\api\service\project;

use app\api\model\ProjectHatch;
use app\api\model\ProjectHatchOrder;
use app\api\service\Token;
use app\api\validate\project\CheckHatch;
use app\lib\exception\ParameterException;
use think\Db;
use think\Exception;

class HatchSer extends Token
{
    /**
     * 1.判断用户权限
     * 2.判断数据
     * 3.判断是否有添加项目的权限
     * 3.没有-提示
     * 4.有-创建信息并修改订单的使用状态
     * 5.返回创建成功
     */

    // 用户ID
    private $uid;

    // 添加信息
    private $postArr;

    // 订单信息
    private $order;


    function __construct($post)
    {
        $this->uid = self::getCurrentUid();
        self::judgeMemberOne();
        (new CheckHatch())->goCheck();
        $this->postArr = $post;
    }

    // 入口文件
    public function entrance()
    {
        return $this->judgeHatchOrder();
    }

    // 判断项目的权限
    private function judgeHatchOrder()
    {
        $info = ProjectHatch::get($this->postArr['id']);
        if($info) {
            if($info['status'] == 2) {
                throw new ParameterException([
                    'msg' => [
                        'hatch' => '项目已经发布，不支持修改'
                    ]
                ]);
            }
            return $this->updateData($info);
        } else {
            $this->order = self::judgeProjectHatch();
            if(!$this->order) {
                throw new ParameterException([
                    'errorCode' => 20002,
                    'msg' => [
                        'hatch' => '没有创建项目的权力'
                    ]
                ]);
            }
            return $this->createData();
        }
    }

    // 创建信息
    private function createData()
    {
        Db::startTrans();
        try{
            $this->postArr['user_id'] = $this->uid;
            $mode = ProjectHatch::create($this->postArr);
            $ProjectHatchOrder = new ProjectHatchOrder();
            $ProjectHatchOrder->save([ 'type' => 2, 'project_hatch_id'=>$mode->id ],[ 'id' => $this->order['id'] ]);
            Db::commit();
            if($this->postArr['status'] == 1) {
                return writeJson(201, [], '添加成功！');
            }else {
                return writeJson(201, [], '发布成功！');
            }
        }
        catch (Exception $ex) {
            //回滚事务
            Db::rollback();
            throw $ex;
        }
    }

    // 修改信息
    private function updateData($info)
    {
        $ProjectHatch = new ProjectHatch();
        $ProjectHatch->allowField(true)
            ->save($this->postArr,[ 'id' => $info['id'] ]);
        if($this->postArr['status'] == 1) {
            return writeJson(202, [], '修改成功！');
        }else {
            return writeJson(202, [], '发布成功！');
        }
    }
}